<?php

namespace app\index\controller;

use app\index\job\JobActivity;
use think\Cache;
use think\Controller;
use think\Db;
use think\Loader;
use think\Queue;
use think\Request;
use think\Validate;

class Api extends Controller
{
    public function login()
    {
        $input = Request()->param();

        $code = $input['code'];

        if (empty($code)) apiReturn(2, '登录失败');

        $appid = C('XCX_APPID');
        $secret = C('XCX_SECRET');
        $grant_type = 'authorization_code';
        $url = 'https://api.weixin.qq.com/sns/jscode2session?';

        $param = [
            'appid' => $appid,
            'secret' => $secret,
            'js_code' => $code,
            'grant_type' => $grant_type
        ];
        $param_str = http_build_query($param);
        $url .= $param_str;

        $user_data = json_decode(file_get_contents($url));

        $openid = $user_data->openid;
        $info = Db::name('user')->where(['openid' => $openid])->find();
        if ($info) {
            // 检查用户
            if ($info['status'] == 2) apiReturn(2, '您的账号已被禁用');

            $user_id = $info['id'];
        } else {
            // 注册新用户
            $data = [
                'username' => '微信用户',
                'openid' => $openid,
                'create_time' => time()
            ];
            $user_id = Db::name('user')->insertGetId($data);
        }

        apiReturn(1, '登录成功', $user_id);
    }

    public function getPlanInfo()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $user_plan_list = Db::name('user_plan')->field('type')->where(['user_id' => $user_id])->select();

        $type_arr = array_column($user_plan_list, 'type');

        $data = [
            'type_arr' => $type_arr,
            'complete_count' => count($user_plan_list)
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    public function completePlan()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $type = $input['type'];

        if(empty($user_id)) apiReturn(2,'您还未登录，请先登录');
        if(empty($type)) apiReturn(2,'任务类型缺失');

        $count = Db::name('user_plan')->where(['user_id' => $user_id, 'type' => $type])->count();
        if($count > 0) apiReturn(2,'您已经完成过该任务');

        $data = [
            'user_id' => $user_id,
            'type' => $type,
            'complete_time' => time()
        ];

        $res = Db::name('user_plan')->insert($data);

        if($res){
            $complete_count = Db::name('user_plan')->where(['user_id' => $user_id])->count();

            apiReturn(1,'任务完成', $complete_count);
        }else{
            apiReturn(2,'任务失败');
        }

    }

}
